// 引入 MongoDB 中间件
const mongoose = Require('mongoose');
// 初始化 MongoDB 格式化程序
const Schema = mongoose.Schema;


const api = require('./api.js');
const _modal = require('./modal.js');
const note = require('./note.js');
const image = require('./image.js');
const url = require('./url.js')



// 创建数据库代理方法
var DataBase = function (options) {
    this.options = options;
    // 基本设置
    var username = this.options.username;
    var password = this.options.password;
    var ip = this.options.ip;
    var port = this.options.port;
    var DBName = this.options.DBName;
    // var DBURL = this.options.DBURL; 
    // var PorjectName = 'API';

    this.module = null;
    // 错误信息 (链接未完成时)
    this.DBMessage = { message: 'HODE ON' };

    var DBURL = 'mongodb://';

    // MongoDB 数据库可不输入用户名及密码
    if (username && password) {
        DBURL = DBURL + username + ':' + password + '@';
    };

    // 创建完整数据库链接
    DBURL = DBURL + ip + ':' + (port ? port : '80') + '/' + DBName;

    // 链接数据库
    mongoose.connect(DBURL, { config: { autoIndex: false } });

    this.openEvent = function () { };

    // 当数据库发生错误时
    mongoose.connection.on("error", (error) => {
        alert(error.message);
        this.openEvent('数据库连接错误');
        this.DBMessage = error.message;
    });
    this.api = {};
    this.note = {};
    this.modal = {};
    this.image = {};
    this.url = {};


    // 当数据库成功链接是
    mongoose.connection.on("open", () => {
        this.DBMessage.message = false;
        this.api = new api(mongoose, Schema, 'API');
        this.note = new note(mongoose, Schema, 'Note');
        this.modal = new _modal(mongoose, Schema, 'Modal');
        this.image = new image(mongoose, Schema, 'Image');
        this.url = new url(mongoose, Schema, 'URL');
        this.openEvent();
    });
};
DataBase.prototype.onOpen = function (event) {
    this.openEvent = event;
};
module.exports = function (options) {
    return new DataBase(options);
};